package com.zues.thread.lock.cas.atomic;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 字段更新器
 * 演示原子引用，对Object进行原子操作，提供一种读和写都是原子性的对象引用变量
 * @author zues
 * @date 3/11/2025 9:09 下午
 */
public class AtomicReferenceDemo {

    public static void main(String[] args) {
        Student s1 = new Student(33, "小李");
        //创建原子引用包装类
        AtomicReference<Student> atomicReference = new AtomicReference<>();
        //设置主存共享变量为s1
        atomicReference.set(s1);

        //比较并交换，如果现在主物理内存的值为小李，那么交换为小花
        while (true){
            Student s2 = new Student(34, "小花");
            if(atomicReference.compareAndSet(s1, s2)){
                break;
            }
        }

        System.out.println(atomicReference.get());
    }


}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student{
    private int id;
    private String name;
}
